package com.kfm.servlet;

import com.kfm.dao.DeptDao;
import com.kfm.model.Dept;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/dept")
public class DeptServlet extends HttpServlet {

    private DeptDao deptDao = new DeptDao();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 查询数据库信息
        try {
            List<Dept> depts = deptDao.selectAll();
            resp.setCharacterEncoding("UTF-8");
            resp.setContentType("text/html;charset=UTF-8");
            String html = "<style>table, tr,td{border:1px solid black;}</style>";
            html += "<table>"
                    + "<tr>"
                    + "<td>id</td>"
                    + "<td>name</td>"
                    + "<td>region_id</td>"
                    + "</tr>";
            for (Dept dept : depts) {
                html += "<tr>" +
                        "<td>" + dept.getId() + "</td>" +
                        "<td>" + dept.getName() + "</td>" +
                        "<td>" + dept.getRegion_id() + "</td>" +
                        "</tr>";
            }
            html = html + "</table>";
            PrintWriter writer = resp.getWriter();
            writer.write(html);
            writer.flush();
            writer.close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
